import axios from 'axios'
import {Message, Notification} from 'element-ui'
import router from '@/router/index'
import i18n from "@/locale";
import {cleanCache} from "@/utils/tools";
import {addRequestPending, removeRequestPending,} from '@/utils/cacelRequest'

const baseUrl = process.env.NODE_ENV === 'development' ? '/api' : window.origin
// 创建axios实例

const service = axios.create({
    timeout: 1000 * 60, // 请求超时时间ss
    baseURL: baseUrl
})
const codeMessage = {
    403: i18n.t('当前账户无此操作权限，请联系管理员'),
    404: i18n.t('发出的请求针对的是不存在的记录，服务器没有进行操作'),
    500: i18n.t('服务器发生错误，请稍后再试'),
    502: i18n.t('网关错误'),
    503: i18n.t('服务不可用，服务器暂时过载或维护'),
    504: i18n.t('网关超时'),
    1000: i18n.t('连接超时'),
    1001: i18n.t('登录超时,请重新登录'),
};
// request拦截器
service.interceptors.request.use(config => {
    addRequestPending(config)
    const lang = localStorage.getItem('locale')
    const token = sessionStorage.getItem('token')
    if (token) config.headers.sysToken = token
    config.headers.LANGUAGE = lang || process.env.VUE_APP_LOCAL || 'zh_CN'
    return config
}, error => {
    Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
    async response => {
        const {data, config} = response
        removeRequestPending(config)
        if (data.code !== '' && data.code !== undefined) {
            if (data.code === 1001) {
                Message({
                    type: 'error',
                    message: codeMessage[data.code],
                    duration: 5 * 1000
                })
                // 防止重复跳转
                if (router.currentRoute.path !== '/login') {
                    await router.push('/login')
                }
                // 清除缓存
                cleanCache()
                console.error('login timeout!')
                return response.data
            } else if (data.code === 4004) {
                Notification.error({
                    title: '403',
                    message: codeMessage[403],
                    duration: 1000 * 5
                });
            } else if (data.code !== 1) {
                Message({
                    type: 'error',
                    message: data.message || '',
                    duration: 5 * 1000
                })
                return response.data
            }
        }
        return response.data
    },
    error => {
        let code
        try {
            code = error.response.status
        } catch {
            //请求超时
            if (error.code === 'ECONNABORTED') {
                code = 1000
            }
        }
        removeRequestPending(error.config || {})
        console.error(error)
        if (code) {
            Message({
                message: codeMessage[code] ? code + ' ' + codeMessage[code] : error,
                type: 'error',
                duration: 5 * 1000
            })
        }
        // 接口错误返回错误码
        return {code: 0}
    }
)

export default service
